<?php

/**
 * This is the model class for table "{{article}}".
 *
 * The followings are the available columns in table '{{article}}':
 * @property integer $arc_id
 * @property string $arc_cid
 * @property string $arc_title
 * @property integer $arc_iscomment
 * @property integer $arc_isrecommend
 * @property integer $arc_ctype
 * @property integer $arc_author
 * @property integer $arc_hits
 * @property integer $arc_created
 * @property integer $arc_update
 * @property string $arc_tags
 * @property integer $arc_state
 * @property string $arc_content
 */
class Article extends CActiveRecord
{
	const STATUS_LOCK		= 0; 	//锁定，未通过审核
	const STATUS_DRIFT 		= 1;	//存草稿	
	const STATUS_ACHIVE		= 2; 	//存档
	const STATUS_PUBLISHED	= 3; 	//发布
    const STATUS_TRASH      = 4;    //回收站
	
	const COMMENT_ALLOW	= 1;		//允许评论
	const COMMENT_CANCEL = 0;		//取消评论
	
	const RECOMMEND_ALLOW = 1;		//允许推荐
	const RECOMMEND_CANCEL = 0;		//取消推荐
	
	private static $_items=array();
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return Article the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{article}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('arc_cid, arc_title, arc_iscomment,arc_isrecommend, arc_state, arc_content', 'required'),
			array('arc_iscomment, arc_isrecommend, arc_ctype, arc_author, arc_hits, arc_update, arc_state', 'numerical', 'integerOnly'=>true),
			array('arc_cid, arc_title', 'length', 'max'=>200),
			array('arc_tags', 'length', 'max'=>100),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('arc_id, arc_cid, arc_title, arc_iscomment, arc_ctype, arc_author, arc_hits, arc_created, arc_update, arc_tags, arc_state, arc_content', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'author'=>array(self::BELONGS_TO, 'User', 'arc_author'),
			'comment'=>array(self::HAS_MANY, 'Comment', 'com_aid'),
			'category'=>array(self::BELONGS_TO,'Category','arc_cid')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'arc_id' => Yii::t('article','Id'),
			'arc_cid' => Yii::t('article','Category'),
			'arc_title' => Yii::t('article','Title'),
			'arc_iscomment' => Yii::t('article','Comments'),
			'arc_isrecommend' => Yii::t('article','Recommend'),
			'arc_ctype'	=> Yii::t('article','Content Type'),
			'arc_author' => Yii::t('article','Author'),
			'arc_hits' => Yii::t('article','Hits'),
			'arc_created' => Yii::t('article','Created'),
			'arc_update' => Yii::t('article','Update'),
			'arc_tags' => Yii::t('article','Tags'),
			'arc_state' => Yii::t('article','State'),
			'arc_content' => Yii::t('article','Content'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

//		$criteria->compare('arc_id',$this->arc_id);
		$criteria->compare('arc_cid',$this->arc_cid,true);
		$criteria->compare('arc_title',$this->arc_title,true);
		$criteria->compare('arc_iscomment',$this->arc_iscomment);
		$criteria->compare('arc_isrecommend',$this->arc_isrecommend);
		$criteria->compare('arc_author',$this->arc_author);
		$criteria->compare('arc_hits',$this->arc_hits);
//		$criteria->compare('arc_created',$this->arc_created);
//		$criteria->compare('arc_update',$this->arc_update);
		$criteria->compare('arc_tags',$this->arc_tags,true);
		$criteria->compare('arc_state',$this->arc_state);
		$criteria->compare('arc_content',$this->arc_content,true);
		
		$criteria->order = "arc_created DESC";

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>5
			)
			
		));
	}
	
	public function getNewsState($state)
	{
		switch ($state) {
			case self::STATUS_ACHIVE:
			 	return Yii::t('common','ACHIVE');
				break;
			case self::STATUS_DRIFT:
				return Yii::t('common','DRIFT');
				break;
			case self::STATUS_LOCK:
				return Yii::t('common','LOCK');
				break;
			case self::STATUS_PUBLISHED:
				return Yii::t('common','PUBLISHED');
				break;
		}
	}
	
	public function generateStateDropdownList()
	{
		return array(
			self::STATUS_PUBLISHED=>$this->getNewsState(self::STATUS_PUBLISHED),
			self::STATUS_ACHIVE=>$this->getNewsState(self::STATUS_ACHIVE),
			self::STATUS_DRIFT=>$this->getNewsState(self::STATUS_DRIFT),
			self::STATUS_LOCK=>$this->getNewsState(self::STATUS_LOCK)
		);
	}
	
	public function getCommentState($state)
	{
		
		switch ($state) {
			case self::COMMENT_ALLOW:
			 	return Yii::t('common','ALLOW');
				break;
			case self::COMMENT_CANCEL:
				return Yii::t('common','CANCEL');
				break;

		}
	}
	
	public function generateCommentStateDropdownList()
	{
		return array(
			self::COMMENT_ALLOW=>self::getCommentState(self::COMMENT_ALLOW),
			self::COMMENT_CANCEL=>self::getCommentState(self::COMMENT_CANCEL)
		);
	}
	public function getRecommendState($state)
	{
		
		switch ($state) {
			case self::RECOMMEND_ALLOW:
			 	return Yii::t('common','ALLOW');
				break;
			case self::RECOMMEND_CANCEL:
				return Yii::t('common','CANCEL');
				break;

		}
	}
	
	public function generateRecommendStateDropdownList()
	{
		return array(
			self::RECOMMEND_ALLOW=>self::getCommentState(self::RECOMMEND_ALLOW),
			self::RECOMMEND_CANCEL=>self::getCommentState(self::RECOMMEND_CANCEL)
		);
	}
		
	public function getNewsStatistics($ctype = Category::CONTENT_STORY)
	{
// 		$start = microtime(true);
// 		$cache = Yii::app()->dbCache;
		
// 		$unique = UtilTools::generateUniqueId(__CLASS__.__METHOD__.$ctype);
		
// 		if ($cache->get($unique) === false)
// 		{
//			echo "Hello";
			
			$arr = array();
			$total = Article::model()->count('arc_ctype = '.$ctype);
			$arr['total'] = $total;
			$published = Article::model()->findAll('arc_state = '.Article::STATUS_PUBLISHED.' AND arc_ctype = '.$ctype);
			$arr['published'] = count($published);
			$draft = Article::model()->findAll('arc_state = '.Article::STATUS_DRIFT.' AND arc_ctype = '.$ctype);
			$arr['draft'] = count($draft);
			$lock = Article::model()->findAll('arc_state = '.Article::STATUS_LOCK.' AND arc_ctype = '.$ctype);
			$arr['lock'] = count($lock);
			$achive = UtilTools::getDirectorySize('.'.Yii::app()->params['autoSavePath']);
			$arr['achive'] = $achive['count'];		

// 			$cache->set($unique, $arr ,24*3600, new CDbCacheDependency('SELECT * FROM {{article}}'));
// 		}
		
// 		$end = microtime(true);
		
//		echo $unique.($end - $start);
		
//		UtilTools::dump($cache->get($unique));
		
// 		return $cache->get($unique);
		

		return $arr; 
	}
	
	public function getCategoryName($id)
	{
		$model = Category::model()->findByPk($id);
		return $model->cate_name;
	}
	
	public function getCategoryLink($cid, $action = 'list')
	{
		$link = "";
		foreach(explode(',', $cid) as $id){
			$link .= '<a href="'.Yii::app()->createUrl($action,array('id'=>$id, 'c'=>urlencode(self::getCategoryName($id)))).'">'.self::getCategoryName($id).'</a>&nbsp;&nbsp;';
		}
		return $link;
	}
	
	/**
	 * 
	 * Enter description here ...
	 */
	public function getGridNewsTitle()
	{
		$html = "";
		$html .= '<a href="'.Yii::app()->createUrl('edit',array('id'=>$this->arc_id)).">".$this->arc_title."</a><br />删除";
		return $html;
	}	
	
	public function getPreviewNews($id)
	{
		$model = self::model()->find('arc_id < :arc_id ORDER BY arc_id DESC',array(':arc_id'=>$id));
		return $model;
	}
	
	public function getNextNews($id)
	{
		$model = self::model()->find('arc_id > :arc_id ORDER BY arc_id ASC',array(':arc_id'=>$id));
		return $model;		
	}
	
    //读取存档文件信息
    function ReadAchive($file)
    {
    	
       	if (!file_exists($file))
    		die("[Error:{'file is not exists'}]");
    	
    	$data = file_get_contents($file);
//    	echo $data;
    	$dataArr = explode('|#-#-#-#|', $data);
//    	var_dump($dataArr);
    	
    	
    	$result = array();
//    	echo "<br />";
    	foreach ($dataArr as $arr){
    		$pos = strpos($arr,':');
    		$key = substr($arr, 0, $pos);
    		$value = substr($arr, $pos+1,strlen($arr));
//    		echo $key.'=>'.$value."<br />";
    		
    		$matches = array();
//			$str = "Article[arc_created]:2011-05-02 03\:40\:33";
			$pattern = "/([A-Za-z]+)\[(\w+_\w+)\]/";
			preg_match($pattern, $key, $matches);
			
			$value = str_replace('\:', ':', $value);
			$value = str_replace('\;', ';', $value);
			
			$result[$matches[1]][$matches[2]]= $value;
    	}
    	
    	
    	return $result;
    }	
    
    //获取所有存档文件信息
    public function getAllAchiveInfo()
    {
    	$achiveInfo = array();
    	$path = '.'.Yii::app()->params['autoSavePath'];
    	$dir = dir($path);
    	$i = 0;
    	while (false !== ($entry = $dir->read())) {
    		if(!($entry == '.' || $entry == '..')){
    			$file =  $dir->path.$entry;
    			$achiveInfo[] = $this->ReadAchive($file);
    			$achiveInfo[$i]['Article']['id'] = substr($entry,0,strpos($entry, '.'));
    			$i++;
    		}
    	}
    	
    	return $achiveInfo;
    }
    
    //获取存档片段
    public function getAllAchiveInfoSlice($offset = 5, $start = 0)
    {
//    	$start = microtime(true);
//   	
//    	$cache = Yii::app()->fileCache;
//    	
//    	$unique = UtilTools::generateUniqueId('achive'.$offset.$start);
//    	
//    	if($cache->get($unique) === false )
//    	{
//    		
//    		echo __CLASS__.__METHOD__;
	    	$achive = array();
	    	
			$result = $this->getAllAchiveInfo();
			
	//		array_slice()
			foreach ($result as $data){
				$achive[] = $data['Article'];
			}
			
			$data = array_slice($achive, $start, $offset);
			$data = json_decode(json_encode($data));
			
//			$cache->set($unique, $data, 3600*24, new CDirectoryCacheDependency('./public/autosave'));
//    	}
//    	
//    	$end = microtime(true);
//    	
//    	echo $unique.($end-$start);
//    	
//    	UtilTools::dump($cache->get($unique));
//		
//		return $cache->get($unique);

		return $data;
    }
	
    
    public function getBlogCategoryCount($id)
    {
    	$criteria = new CDbCriteria(array(
            'condition'=>"arc_cid like '%,{$id}' OR arc_cid like '%,{$id},' OR arc_cid like '%{$id},' OR arc_cid = '{$id}'",
            'order'=>'arc_created DESC',
        ));
        
        $criteria->addCondition('arc_state = '.Article::STATUS_PUBLISHED);
        
        $model = self::model()->count($criteria);
        
        return  $model;
    }
	
	/**
	 * This is invoked before the record is saved.
	 * @return boolean whether the record should be saved.
	 */
	protected function beforeSave()
	{
		if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
				$this->arc_update=time();
				$this->arc_author = Yii::app()->user->id;
				
				$this->arc_hits = 0;
			}
			else
				$this->arc_update=time();
			return true;
		}
		else
			return false;
	}
	

	
}